package k8ssvc

import (
	"bytes"
	"context"
	"errors"
	"strings"

	v1 "k8s.io/api/core/v1"
	metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
	"k8s.io/client-go/kubernetes"
	"k8s.io/client-go/kubernetes/scheme"
	"k8s.io/client-go/rest"
	"k8s.io/client-go/tools/remotecommand"
)

type podAdapter struct {
	clientSet *kubernetes.Clientset
	config    *rest.Config
	ctx       context.Context
	pod       v1.Pod
}

func (m podAdapter) Delete() error {
	return m.clientSet.CoreV1().Pods(m.pod.Namespace).Delete(m.ctx, m.pod.Name, metav1.DeleteOptions{})
}

func (m podAdapter) Exec(args ...string) (string, error) {
	restURL := m.clientSet.CoreV1().RESTClient().Post().Resource("pods").Name(m.pod.Name).Namespace(m.pod.Namespace).SubResource("exec").VersionedParams(&v1.PodExecOptions{
		Command: args,
		Stdin:   true,
		Stdout:  true,
		Stderr:  true,
		TTY:     false,
	}, scheme.ParameterCodec).URL()
	exec, err := remotecommand.NewSPDYExecutor(m.config, "POST", restURL)
	if err != nil {
		return "", err
	}

	var stdout, stderr bytes.Buffer
	err = exec.Stream(remotecommand.StreamOptions{
		Stdin:  strings.NewReader(""),
		Stdout: &stdout,
		Stderr: &stderr,
	})
	if err != nil {
		return "", err
	}

	if stderr.Len() > 0 {
		return "", errors.New(
			stderr.String(),
		)
	}

	return stdout.String(), nil
}

func (m podAdapter) GetData() v1.Pod {
	return m.pod
}
